package cn.itzzx.lagou.netty.rpc.provider;

import cn.itzzx.lagou.netty.rpc.common.coder.RpcDecoder;
import cn.itzzx.lagou.netty.rpc.common.coder.RpcEncoder;
import cn.itzzx.lagou.netty.rpc.common.pojo.RpcRequest;
import cn.itzzx.lagou.netty.rpc.common.serializer.JSONSerializer;
import cn.itzzx.lagou.netty.rpc.common.service.UserService;
import cn.itzzx.lagou.netty.rpc.handler.UserServiceHandler;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import org.apache.curator.framework.CuratorFramework;
import org.springframework.stereotype.Service;

import java.net.InetSocketAddress;
import java.util.Random;

/**
 * TODO 写点注视啦
 *
 * @author Martin
 * @date 2020-06-17
 * @see 1.0
 */
@Service
public class UserServiceImpl implements UserService {

    @Override
    public String sayHello(String msg) {
        System.out.println("收到客户端发送数据: " + msg);
        //返回客户端信息
        Random random = new Random();
        int s = random.nextInt(1000) % (1000 + 1);
        try {
            // 模拟0～1秒延迟
            Thread.sleep(s);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("收到客户端发送数据: "+msg);
        //返回客户端信息
        return "127.0.0.1:8089 节点发送 success";
    }

    public static void startServer(String ip, int port, CuratorFramework build) throws InterruptedException {
        //1 创建两个线程对象
        NioEventLoopGroup bossGroup = new NioEventLoopGroup();
        NioEventLoopGroup workerGroup = new NioEventLoopGroup();

        //2 创建服务端的启动引导对象
        ServerBootstrap serverBootstrap = new ServerBootstrap();
        serverBootstrap.group(bossGroup, workerGroup)
                .channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel nioSocketChannel) throws Exception {
                        //获取管道对象
                        ChannelPipeline pipeline = nioSocketChannel.pipeline();
                        //给管道对象pipeLine 设置编码
                        pipeline.addLast(new StringEncoder());
                        //设置解码器 解析客户端传过来的参数
                        pipeline.addLast(new RpcDecoder(RpcRequest.class, new JSONSerializer()));
                        //把我们自顶一个ChannelHander添加到通道中
                        pipeline.addLast(new UserServiceHandler(build));
                    }
                });

        //4.绑定端口
        serverBootstrap.bind(new InetSocketAddress(ip, port)).sync();

        System.out.println("netty start complete...");
    }

}
